﻿
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AntdUI;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Menu;
using BusinessService.Plugin.Entity;
using static System.ComponentModel.Design.ObjectSelectorEditor;
using WindowsForm.CustomControl;
using EMSSevice;
using Microsoft.Extensions.DependencyInjection;
using Sunny.UI;
using BusinessService.Plugin.DataSource.Sqlite;
using BusinessService.Plugin.DataSource.Sqlite.Dtos;
using IFM.Core;
using SqlSugar;
using Elephant.FormUtils;
using System.Net.Sockets;
using static Sunny.UI.MathEx;
using BusinessService.Plugin.Const;
using BusinessService.Plugin.Services;
namespace WindowsForm.Forms
{
    public partial class DialogBox : Form
    {
        private BackService _backService => Program.IOC.GetRequiredService<BackService>();

        private SqliteLibrary _repSqlite => Program.IOC.GetRequiredService<SqliteLibrary>();
        //条件筛选表的字段
        DataGridViewComboEditBoxColumn comboColumn = new();
        DataGridViewComboEditBoxColumn comboColumn1 = new();
        DataGridViewComboEditBoxColumn textColumn = new();
        DataGridViewComboEditBoxColumn TypeColumn = new();
        DataGridViewButtonColumn buttonColumn = new();
        //选择表的字段
        DataGridViewComboEditBoxColumn SelectFieldColumn = new();
        DataGridViewComboEditBoxColumn FieldAliasColumn = new();
        DataGridViewComboEditBoxColumn FieldSortColumn = new();
        DataGridViewComboEditBoxColumn GroupColumn = new();
        DataGridViewComboEditBoxColumn ComputeColumn = new();

        DataGridViewButtonColumn buttonColumn2 = new();
        public DialogBox()
        {
            InitializeComponent();
            #region 表格初始化
            Where_Table.Init();
            //(where表格)不自动生成列
            Where_Table.AutoGenerateColumns = false;
            comboColumn.HeaderText = "字段";
            comboColumn.Name = "字段";
            comboColumn1.HeaderText = "比较";
            comboColumn1.Name = "比较";
            textColumn.HeaderText = "设定值";
            textColumn.Name = "设定值";
            TypeColumn.HeaderText = "类型";
            TypeColumn.Name = "类型";
            buttonColumn.HeaderText = "操作";
            buttonColumn.Name = "操作";
            //// 向下拉列表中添加选项  
            comboColumn1.Items.Add("=");
            comboColumn1.Items.Add("!=");
            comboColumn1.Items.Add(">");
            comboColumn1.Items.Add(">=");
            comboColumn1.Items.Add("<");
            comboColumn1.Items.Add("<=");
            comboColumn.Items.Clear();
            SelectFieldColumn.Items.Clear();
            _repSqlite.GetColumnInfosByTableName(select1.Text).ForEach(x =>
            {
                comboColumn.Items.Add(x.DbColumnName);
                SelectFieldColumn.Items.Add(x.DbColumnName);
            });

            foreach (var item in DateTimeEnum.timeFormat)
            {
                textColumn.Items.Add(item.ToString());
            }

            buttonColumn.Text = "删除"; // 注意：这通常不会改变按钮的显示文本
            //buttonColumn.FlatStyle = FlatStyle.Flat;
            buttonColumn.DefaultCellStyle.ForeColor = Color.Red;
            buttonColumn.UseColumnTextForButtonValue = true; // 通常不推荐用于按钮列  
            Where_Table.Columns.Add(comboColumn);
            Where_Table.Columns.Add(comboColumn1);
            Where_Table.Columns.Add(textColumn);
            Where_Table.Columns.Add(TypeColumn);
            Where_Table.Columns.Add(buttonColumn);


            // (Select表格)不自动生成列
            Select_Table.Init();
            //不自动生成列
            Select_Table.AutoGenerateColumns = false;
            Select_Table.ReadOnly = false;
            SelectFieldColumn.HeaderText = "字段";
            SelectFieldColumn.Name = "字段";
            FieldAliasColumn.HeaderText = "别名";
            FieldAliasColumn.Name = "别名";
            FieldSortColumn.HeaderText = "排序方式";
            FieldSortColumn.Name = "排序方式";
            GroupColumn.HeaderText = "分组字段";
            GroupColumn.Name = "分组字段";
            ComputeColumn.HeaderText = "统计方式";
            GroupColumn.Name = "统计方式";

            buttonColumn2.HeaderText = "操作";
            buttonColumn2.Name = "操作";
            buttonColumn2.Text = "删除"; // 注意：这通常不会改变按钮的显示文本

            foreach (var item in Match.Character)
            {

                TypeColumn.Items.Add(item);

            }
            //是否分组选择
            GroupColumn.Items.Add("是");
            GroupColumn.Items.Add("否");

            //计算方式选择
            ComputeColumn.Items.Add("求和");
            ComputeColumn.Items.Add("平均");
            ComputeColumn.Items.Add("最大值");
            ComputeColumn.Items.Add("最小值");

            FieldSortColumn.Items.Add("顺序");
            FieldSortColumn.Items.Add("倒序");
            buttonColumn2.DefaultCellStyle.ForeColor = Color.Red;
            buttonColumn2.UseColumnTextForButtonValue = true; // 通常不推荐用于按钮列  
            Select_Table.Columns.Add(SelectFieldColumn);
            Select_Table.Columns.Add(FieldAliasColumn);
            Select_Table.Columns.Add(GroupColumn);//添加分组列
            Select_Table.Columns.Add(ComputeColumn);//添加计算方式列



            Select_Table.Columns.Add(FieldSortColumn);
            Select_Table.Columns.Add(buttonColumn2);
            #endregion
        }
        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void DialogBox_Load(object sender, EventArgs e)
        {


            var tables = _repSqlite.GetTableInfoList();
            foreach (var table in tables)
            {
                select1.Items.Add(table);
            }
            manysSelect.Items.Add("是");
            manysSelect.Items.Add("否");
            manysSelect.Text = "是";

            if (Tag != null)
            {


                var DBtables = _repSqlite.jointQuery((long)Tag);

                //数据库查询设置回显
                if (!SqlFunc.IsNullOrEmpty(DBtables) && DBtables.P.V_ProtocolType.Equals("DataBase"))
                {
                    if (!string.IsNullOrEmpty(DBtables.P.Link))
                    {
                        comboColumn.Items.Clear();
                        SelectFieldColumn.Items.Clear();
                        _repSqlite.GetColumnInfosByTableName(DBtables.P.Link).ForEach(x =>
                        {
                            comboColumn.Items.Add(x.DbColumnName);
                            SelectFieldColumn.Items.Add(x.DbColumnName);
                        });
                    }

                    inputName.Text = DBtables.P.Name;
                    select1.Text = DBtables.P.Link;
                    if (!string.IsNullOrEmpty(DBtables.P.SingleAndDouble))
                    {
                        manysSelect.Text = DBtables.P.SingleAndDouble;
                    };

                    if (!SqlFunc.IsNullOrEmpty(DBtables.F))
                    {
                        int i = 0;
                        foreach (var item in DBtables.F)
                        {
                            Where_Table.AddRow();
                            Where_Table.Rows[i].Cells[0].Value = item.SelectItem;
                            Where_Table.Rows[i].Cells[1].Value = item.CompareAction;
                            Where_Table.Rows[i].Cells[2].Value = item.TargetValue;
                            Where_Table.Rows[i].Cells[3].Value = item.CSharpTypeName;
                            i++;
                        }
                    }
                    if (!SqlFunc.IsNullOrEmpty(DBtables.S))
                    {
                        int i = 0;
                        foreach (var item in DBtables.S)
                        {
                            Select_Table.AddRow();
                            Select_Table.Rows[i].Cells[0].Value = item.SelectField;
                            Select_Table.Rows[i].Cells[1].Value = item.FieldAlias;
                            Select_Table.Rows[i].Cells[2].Value = item.IsGroupBy;
                            Select_Table.Rows[i].Cells[3].Value = item.ComputeMode;
                            Select_Table.Rows[i].Cells[4].Value = item.FieldSort;
                            i++;
                        }
                    }
                }




                var Others = _repSqlite.sqliteQuery((long)Tag);
                if (Others != null)
                {

                    switch (Others.V_ProtocolType)
                    {

                        case "Socket":
                            TCP_Name.Text = Others.Name;
                            TCP_select.Text = Others.Link;
                            break;
                        default:
                            break;
                    }
                }

            }

            AllSetQueryInput input = new AllSetQueryInput();
            var param = _repSqlite.AllSetQuery(input);//查询所有的设置参数
            //socket回显
            var socketIPList = param.Where(x => x.N_Role == 1 && x.V_ProtocolType.Equals("Socket"))
                .Select(x => x.V_Name)
                .ToList();//接收数据端通讯上下文配置集合
            socketIPList.ForEach(x =>
            {
                TCP_select.Items.Add(x);
            });
            //MQTT回显
            var MQTTList = param.Where(x => x.N_Role == 1 && x.V_ProtocolType.Equals("MQTT"))
            .Select(x => x.V_Name)
            .ToList();//接收数据端通讯上下文配置集合
            MQTTList.ForEach(x =>
            {
                MQTTselect.Items.Add(x);
            });

            //Http回显
            var HttpList = param.Where(x => x.N_Role == 1 && x.V_ProtocolType.Equals("Http"))
            .Select(x => x.V_Name)
            .ToList();//接收数据端通讯上下文配置集合
            HttpList.ForEach(x =>
            {
                Http_select.Items.Add(x);
            });



        }
        private void select1_SelectedIndexChanged(object sender, int value)
        {
            comboColumn.Items.Clear();
            SelectFieldColumn.Items.Clear();
            _repSqlite.GetColumnInfosByTableName(select1.Text).ForEach(x =>
            {
                comboColumn.Items.Add(x.DbColumnName);
                SelectFieldColumn.Items.Add(x.DbColumnName);
            });
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Where_Table.AddRow();
        }
        private void uiDataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                DataGridViewColumn column = Where_Table.Columns[e.ColumnIndex];
                if (column is DataGridViewButtonColumn)
                {
                    //这里可以编写你需要的任意关于按钮事件的操作
                    //MessageBox.Show("按钮被点击");           
                    Where_Table.Rows.RemoveAt(e.RowIndex);//删除当前行
                }
            }
        }
        private void button4_Click(object sender, EventArgs e)
        {
            Select_Table.AddRow();
        }
        private void uiDataGridView2_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                DataGridViewColumn column = Select_Table.Columns[e.ColumnIndex];
                if (column is DataGridViewButtonColumn)
                {
                    //这里可以编写你需要的任意关于按钮事件的操作
                    //MessageBox.Show("按钮被点击");           
                    Select_Table.Rows.RemoveAt(e.RowIndex);//删除当前行
                }
            }
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            ParameterSettings parameterSettings = new ParameterSettings() //主表的数据
            {
                CreateTime = DateTime.Now,
                Link = select1.Text,
                Name = inputName.Text,
                SingleAndDouble = manysSelect.Text,
                V_ProtocolType = "DataBase",
            };
            //筛选条件保存
            List<FilterTable> whereEx = new List<FilterTable>();
            for (int i = 0; i < Where_Table.RowCount; i++)
            {
                FilterTable child = new();
                child.SelectItem = Convert.ToString(Where_Table.Rows[i].Cells[0].Value);
                child.CompareAction = Convert.ToString(Where_Table.Rows[i].Cells[1].Value);
                child.TargetValue = Convert.ToString(Where_Table.Rows[i].Cells[2].Value);
                child.CSharpTypeName = Convert.ToString(Where_Table.Rows[i].Cells[3].Value);
                whereEx.Add(child);
            }
            //字段保存
            List<SelectFields> fields = new List<SelectFields>();
            for (int i = 0; i < Select_Table.RowCount; i++)
            {
                SelectFields child = new SelectFields();
                child.SelectField = Convert.ToString(Select_Table.Rows[i].Cells[0].Value);
                child.FieldAlias = Convert.ToString(Select_Table.Rows[i].Cells[1].Value);
                child.IsGroupBy = Convert.ToString(Select_Table.Rows[i].Cells[2].Value);
                child.ComputeMode = Convert.ToString(Select_Table.Rows[i].Cells[3].Value);
                child.FieldSort = Convert.ToString(Select_Table.Rows[i].Cells[4].Value);
                fields.Add(child);
            }


            var isGroup = fields.Any(x => x.IsGroupBy.Contains("是"));
            if (isGroup)
            {
                var ComputeModeIsEmpty = fields.Where(x =>
                x.IsGroupBy == string.Empty && x.ComputeMode == string.Empty
                )
                    .Select(x=>x.SelectField)
                    .ToList();
                if (ComputeModeIsEmpty.Count>0)
                {
                    MessageBox.Show($"设置无法保存，因为分组查询不允许出现非聚合列！非聚合列：{string.Join("、",ComputeModeIsEmpty)   }", "严重警告");
                    return;
                }

            }


            SqliteLibraryInput input = new SqliteLibraryInput()
            {
                mainTable = parameterSettings,
                SelectFields = fields,
                whereEx = whereEx,

            };
            var mm = input.ToJsonString();
            if (SqlFunc.IsNullOrEmpty(Tag))
            {
                _repSqlite.SqliteInsert(input);
            }
            else
            {
                input.mainTable.ID = (long)Tag;
                _repSqlite.SqliteUpdate(input);
            }

            //刷新表格数据
            if (DataSetting.RefreshTable != null) DataSetting.RefreshTable();

        }

        private void button3_Click_1(object sender, EventArgs e)
        {
            Where_Table.AddRow();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            ParameterSettings parameterSettings = new ParameterSettings() //主表的数据
            {
                CreateTime = DateTime.Now,
                Link = TCP_select.Text,
                Name = TCP_Name.Text,
                V_ProtocolType = "Socket",
            };
            SqliteLibraryInput input = new SqliteLibraryInput();
            input.mainTable = parameterSettings;
            if (SqlFunc.IsNullOrEmpty(Tag))
            {
                _repSqlite.SqliteInsert(input);
            }
            else
            {
                input.mainTable.ID = (long)Tag;
                _repSqlite.SqliteUpdate(input);
            }
            //刷新表格数据
            if (DataSetting.RefreshTable != null) DataSetting.RefreshTable();
        }

        private void input1_TextChanged(object sender, EventArgs e)
        {

        }

        private void socketSelect_SelectedIndexChanged(object sender, int value)
        {

        }

        private void button8_Click(object sender, EventArgs e)
        {
            ParameterSettings parameterSettings = new ParameterSettings() //主表的数据
            {
                CreateTime = DateTime.Now,
                Link = MQTTselect.Text,
                Name = MQTT_name.Text,
                V_ProtocolType = "MQTT",
            };


            SqliteLibraryInput input = new SqliteLibraryInput();
            input.mainTable = parameterSettings;
            if (SqlFunc.IsNullOrEmpty(Tag))
            {
                _repSqlite.SqliteInsert(input);
            }
            else
            {
                input.mainTable.ID = (long)Tag;
                _repSqlite.SqliteUpdate(input);
            }

            //刷新表格数据
            if (DataSetting.RefreshTable != null) DataSetting.RefreshTable();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            ParameterSettings parameterSettings = new ParameterSettings() //主表的数据
            {
                CreateTime = DateTime.Now,
                Link = Http_select.Text,
                Name = Http_name.Text,
                V_ProtocolType = "Http",
            };
            SqliteLibraryInput input = new SqliteLibraryInput();
            input.mainTable = parameterSettings;
            if (SqlFunc.IsNullOrEmpty(Tag))
            {
                _repSqlite.SqliteInsert(input);
            }
            else
            {
                input.mainTable.ID = (long)Tag;
                _repSqlite.SqliteUpdate(input);
            }
            //刷新表格数据
            if (DataSetting.RefreshTable != null) DataSetting.RefreshTable();
        }

        private void button4_Click_1(object sender, EventArgs e)
        {
            Select_Table.AddRow();
        }

        private void select1_SelectedIndexChanged_1(object sender, int value)
        {

        }

        private void tabPage1_Click(object sender, EventArgs e)
        {

        }

        private void Where_Table_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            // 如果点击的是删除按钮
            if (e.ColumnIndex == Where_Table.Columns["操作"].Index && e.RowIndex >= 0)
            {
                // 删除行
                Where_Table.Rows.RemoveAt(e.RowIndex);
            }
        }

        private void Select_Table_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == Select_Table.Columns["操作"].Index && e.RowIndex >= 0)
            {
                // 删除行
                Select_Table.Rows.RemoveAt(e.RowIndex);
            }
        }

        private void tabPage4_Click(object sender, EventArgs e)
        {

        }
    }
}
